export class SnowflakeHelper {
  private workerId: number; // 机器 ID
  private dataCenterId: number; // 数据中心 ID
  private sequence: number; // 序列号
  private lastTimestamp: number; // 上一次生成 ID 的时间戳

  private readonly maxSequence = 999; // 序列号的最大值，三位数

  constructor(workerId = 1, dataCenterId = 1) {
    this.workerId = workerId;
    this.dataCenterId = dataCenterId;
    this.sequence = 0;
    this.lastTimestamp = -1;
  }

  // 获取当前时间戳（完整时间戳，毫秒级）
  private getTimestamp(): number {
    return Date.now();
  }

  // 等待下一毫秒
  private waitUntilNextMillis(lastTimestamp: number): number {
    let timestamp = this.getTimestamp();
    while (timestamp <= lastTimestamp) {
      timestamp = this.getTimestamp();
    }
    return timestamp;
  }

  // 生成 19 位唯一 ID
  public nextId(): string {
    let timestamp = this.getTimestamp();

    if (timestamp < this.lastTimestamp) {
      throw new Error('Clock moved backwards. Refusing to generate id!');
    }

    if (timestamp === this.lastTimestamp) {
      // 如果在同一毫秒内，递增序列号
      this.sequence = (this.sequence + 1) % (this.maxSequence + 1);
      if (this.sequence === 0) {
        // 序列号用完，等待下一毫秒
        timestamp = this.waitUntilNextMillis(this.lastTimestamp);
      }
    } else {
      // 如果是新的一毫秒，序列号重置为 0
      this.sequence = 0;
    }

    this.lastTimestamp = timestamp;

    // 组合时间戳和序列号
    const baseId = `${timestamp}${this.sequence.toString().padStart(3, '0')}`;

    // 如果不足 19 位，用随机数补齐
    const randomPadding = Math.random()
      .toString()
      .slice(2, 2 + (19 - baseId.length));
    const id = baseId + randomPadding;

    return id;
  }
}
